package com.itboye.eweilisten.fragment;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.itboye.eweilisten.R;
import com.itboye.eweilisten.adapter.TagAdapter;
import com.itboye.eweilisten.adapter.TagThreeAdapter;
import com.itboye.eweilisten.adapter.TagTwoAdapter;
import com.itboye.eweilisten.adapter.WrongAdapter;
import com.itboye.eweilisten.app.MyApplication;
import com.itboye.eweilisten.base.BaseFragment;
import com.itboye.eweilisten.main.MainActivity;
import com.itboye.eweilisten.me.home.ActivityScoreReport;
import com.itboye.eweilisten.me.login.LoginActivity;
import com.itboye.eweilisten.model.SchoolBean;
import com.itboye.eweilisten.model.SouSuoBean;
import com.itboye.eweilisten.presenter.UserPresenter;
import com.itboye.eweilisten.util.flowtalayout.FlowTagLayout;
import com.itboye.eweilisten.util.flowtalayout.OnTagSelectListener;
import com.itboye.eweilisten.util.loadingutil.MAlert;
import com.itboye.eweilisten.util.sputil.Const;
import com.itboye.eweilisten.util.sputil.SPUtils;
import com.itboye.eweilisten.util.widget.IsStringSPUtils;
import com.itboye.eweilisten.util.widget.PopupWindows;
import com.itboye.eweilisten.volley.ResultEntity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * 成绩单
 */

public class SchoolReportFragment extends BaseFragment implements Observer {
    ImageView back;
    TextView tvTitle;
    private boolean isNetAble=true;
    private ListView chengListView;
    PtrClassicFrameLayout commend_anchor_ptr;
    LinearLayout kong_layoout;
    private static TextView tvShiJian,tvSchDanYuan;//时间，单元,
    private WrongAdapter adapter;
    SchoolBean bean;
    private List<SchoolBean.InfoList> lists;
    static UserPresenter presenter;
    List<SouSuoBean> list;

    private static int pgaeNum = 1;
    private static int pageSize = 10;
    String uid;

    private Dialog dialog;// 自定义Dialog
    String tid;

    private static PopupWindows window;
    static FlowTagLayout flowlayoutOne;
    static FlowTagLayout flowLayoutTwo;
    static FlowTagLayout flowLayoutThree;

    private static TagAdapter<String> oneTagAdapter;
    private static TagTwoAdapter<String> twoTagAdapter;
    private static TagThreeAdapter<String> threeTagAdapter;
    List<String> strings = new ArrayList<String>();
    static private TextView oneTitle, twoTitle, threeTitle;
    static TextView tvWancheng;//完成
    static TextView tvReset;//重置

    static int onePosition = 0;//标记选中的书本
    static int twoPosition = 0;//标记选中一级的单元
    static StringBuffer sbXuan = new StringBuffer();//选中的一级项目ID集合
    static StringBuffer sbXuan02 = new StringBuffer();//选中的2级项目ID集合

    static String unit_id="0";//可选,1或2级单元id,不为0时book_id会被忽略,多个以英文逗号分隔
    private int mTimeTag=0;
    @Override
    public int initView() {
        return R.layout.fragment_school;
    }

    @Override
    public void onMyActivityCreated() {
        tvTitle.setText("成绩单");
        back.setVisibility(View.INVISIBLE);
        uid = (String) SPUtils.get(MyApplication.instance, null, Const.ID, "");
        presenter = new UserPresenter(this);
        bean = new SchoolBean();
        list = new ArrayList<>();
        lists = new ArrayList<SchoolBean.InfoList>();
        presenter.onPreSearch(uid, "", "0", "10",IsStringSPUtils.getSid());
        commend_anchor_ptr.setLastUpdateTimeRelateObject(this);
        commend_anchor_ptr.postDelayed(new Runnable() {
            @Override
            public void run() {
                presenter.onSchoolRepor(uid, "0", "0", unit_id, "1", pgaeNum + "", pageSize + "",IsStringSPUtils.getSid());
                commend_anchor_ptr.autoRefresh();//自动刷新
            }
        }, 100);
        commend_anchor_ptr.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {//加载更多的时候
                pgaeNum++;
                presenter.onSchoolRepor(uid, "0", "0", unit_id, "1", pgaeNum + "", pageSize + "",IsStringSPUtils.getSid());
                Log.d("====num==",pgaeNum+"");
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {//刷新开始
                pgaeNum=1;
                presenter.onSchoolRepor(uid, "0", "0", unit_id, "1", pgaeNum + "", pageSize + "",IsStringSPUtils.getSid());
                Log.d("====num==",pgaeNum+"");
            }
        });
        showExtraDialog();
        init();

        //登录的广播
        IntentFilter filter = new IntentFilter(LoginActivity.LOGIN);
        getActivity().registerReceiver(loginReceiver, filter);
        IntentFilter connect_recover = new IntentFilter("connect_recover");
        getActivity().registerReceiver(netBroadcastReceiver,connect_recover);
    }
    BroadcastReceiver loginReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            uid = (String) SPUtils.get(MyApplication.instance, null, Const.ID, "");
            presenter.onSchoolRepor(uid, "0", "0", "0", "1", pgaeNum + "", pageSize + "",IsStringSPUtils.getSid());
            if (adapter!=null){
                adapter.notifyDataSetChanged();
            }
        }
    };


    BroadcastReceiver netBroadcastReceiver= new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("connect_recover")&&intent.getIntExtra("recover",0)==400){
                presenter.onSchoolRepor(uid, "0", "0", unit_id, "1", pgaeNum + "", pageSize + "",IsStringSPUtils.getSid());
            }
        }
    };

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!MainActivity.isShowing2){
            if(!hidden){
                commend_anchor_ptr.autoRefresh();
                MainActivity.isShowing2=true;
            }
        }


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(loginReceiver);
    }
    //ListView的操作
    private void init(){
        chengListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), ActivityScoreReport.class);
                intent.putExtra("unit_id", lists.get(position).getUnit_id());
                intent.putExtra("id", lists.get(position).getId());
                intent.putExtra("type",1);
                startActivity(intent);

            }
        });
        chengListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                tid = lists.get(position).getId();
                dialog.show();
                return true;
            }
        });
    }

    @Override
    public void onClick(View v) {

//        switch (v.getId()) {
//            case R.id.tvSchDanYuan:
//
//                onFna(list, window, strings, getActivity(), tvSchDanYuan);
//                break;
//            case R.id.tvShiJian:
//                clera();
//                tvShiJian.setTextColor(getResources().getColor(R.color.darkgreen));
//                presenter.onSchoolRepor(uid, "0", "0",  "0", "1", pgaeNum + "", pageSize + "",IsStringSPUtils.getSid());
//                break;
//        }
    }

//    private static void clera(){//gray_01
//        tvShiJian.setTextColor(MyApplication.instance.getResources().getColor(R.color.gray_01));
//        tvSchDanYuan.setTextColor(MyApplication.instance.getResources().getColor(R.color.gray_01));
//    }



    @Override
    public void update(Observable o, Object arg) {

        ResultEntity entity = handlerError(arg);
        if (entity != null) {
            if (entity.getEventType() == presenter.SchoolRepor_success) {
                if (pgaeNum == 1) {
                    lists.clear();
                }
                bean = (SchoolBean) entity.getData();
                commend_anchor_ptr.refreshComplete();//设置刷新完成
                lists.addAll(bean.getList());

                if (lists.size() > 0) {
                    adapter = new WrongAdapter(getActivity(), lists);
                    chengListView.setAdapter(adapter);
                    adapter.notifyDataSetChanged();

                    chengListView.setVisibility(View.VISIBLE);
                    commend_anchor_ptr.setVisibility(View.VISIBLE);
                    kong_layoout.setVisibility(View.GONE);
                } else {
                    chengListView.setVisibility(View.GONE);
                    commend_anchor_ptr.setVisibility(View.GONE);
                    kong_layoout.setVisibility(View.VISIBLE);
                //    MAlert.alert("暂无数据");
                }
            }
            if (entity.getEventType() == presenter.SchoolRepor_fail) {
                commend_anchor_ptr.refreshComplete();//设置刷新完成
                MAlert.alert(entity.getData());
            }
            //搜索
            if (entity.getEventType() == presenter.SouSuo_success) {
                list = (List<SouSuoBean>) entity.getData();
            }
            if (entity.getEventType() == presenter.SouSuo_fail) {
                MAlert.alert(entity.getData());
            }
            //删除
            if (entity.getEventType() == presenter.delete_success) {
                Iterator<SchoolBean.InfoList> iterator = lists.iterator();
                while (iterator.hasNext()) {
                    SchoolBean.InfoList bean = iterator.next();
                    if (tid == bean.getId()) {
                        iterator.remove();
                        adapter.notifyDataSetChanged();
                        break;
                    }
                }
            }
            if (entity.getEventType() == presenter.delete_fail) {
                MAlert.alert(entity.getData());
            }
        }
        try {
            dialog.dismiss();
            closeProgressDialog();
        } catch (Exception e) {
        }
    }
    public static void onFna(final List<SouSuoBean> been, PopupWindows windows, final List<String> strings, Context context, View v) {
        strings.clear();

        View view = View.inflate(context, R.layout.add_popup_dialog, null);
        windows = new PopupWindows(context, v, view);
        flowlayoutOne = (FlowTagLayout) view.findViewById(R.id.flowlayoutOne);
        flowLayoutTwo = (FlowTagLayout) view.findViewById(R.id.flowlayoutTwo);
        flowLayoutThree = (FlowTagLayout) view.findViewById(R.id.flowlayoutThree);
        tvWancheng = (TextView) view.findViewById(R.id.tvWancheng);
        tvReset= (TextView) view.findViewById(R.id.tvReset);
        oneTitle = (TextView) view.findViewById(R.id.oneTitle);
        twoTitle = (TextView) view.findViewById(R.id.twoTitle);
        threeTitle = (TextView) view.findViewById(R.id.threeTitle);

        OnWanCheng(tvWancheng,windows);
        //移动研发标签
        oneTagAdapter = new TagAdapter<>(context);//第一级
        twoTagAdapter = new TagTwoAdapter<>(context);//第二级
        threeTagAdapter = new TagThreeAdapter<>(context);//第三级
        flowlayoutOne.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);
        flowLayoutTwo.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);
        flowLayoutThree.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_MULTI);

        flowlayoutOne.setAdapter(oneTagAdapter);
        oneTagAdapter.onlyAddAll(been);

        flowlayoutOne.setOnTagSelectListener(new OnTagSelectListener() {
            @Override
            public void onItemSelect(FlowTagLayout parent, List<Integer> selectedList, int position) {
                onePosition = position;
                MAlert.alert(been.get(position).getBook_name() + "");
                twoTagAdapter.clearAndAddAll(been.get(position).getUnits());
                flowLayoutTwo.setAdapter(twoTagAdapter);
                if (selectedList != null && selectedList.size() > 0) {
                    twoTagAdapter.onlyAddAll(been.get(position).getUnits());

                    twoTitle.setVisibility(View.VISIBLE);
                    flowLayoutTwo.setVisibility(View.VISIBLE);
                } else {
                    twoTagAdapter.clearAndAddAll(been.get(position).getUnits());
                }
            }
        });

        flowLayoutTwo.setOnTagSelectListener(new OnTagSelectListener() {
            @Override
            public void onItemSelect(FlowTagLayout parent, List<Integer> selectedList, int position) {
                //MAlert.alert(been.get(onePosition).getUnits().get(position).getUnit_name()+"");
                String ids = been.get(onePosition).getUnits().get(position).getUnit_id() + ",";

                twoPosition = position;
                threeTagAdapter.clearAndAddAll(been.get(onePosition).getUnits().get(position).getChild());
                flowLayoutThree.setAdapter(threeTagAdapter);

                sbXuan.delete(0, sbXuan.length());
                sbXuan02.delete(0, sbXuan02.length());
                if (selectedList != null && selectedList.size() > 0) {
                    sbXuan.append(ids);
                    threeTagAdapter.onlyAddAll(been.get(onePosition).getUnits().get(position).getChild());

                    threeTitle.setVisibility(View.VISIBLE);
                    flowLayoutThree.setVisibility(View.VISIBLE);

                } else {
                    threeTagAdapter.clearAndAddAll(been.get(onePosition).getUnits().get(position).getChild());
                    // MAlert.alert(selectedList.size() + "");
                }
            }
        });

        flowLayoutThree.setOnTagSelectListener(new OnTagSelectListener() {
            @Override
            public void onItemSelect(FlowTagLayout parent, List<Integer> selectedList, int position) {
                List<com.itboye.eweilisten.model.SouSuoBean.InfounitsOne.Infochild> listChild = been.get(onePosition).getUnits().get(twoPosition).getChild();
                sbXuan02.delete(0, sbXuan02.length());

                for (int i = 0; i < parent.getChildCount(); i++) {
                    if (parent.getChildAt(i).isSelected()) {
                        sbXuan02.append(listChild.get(i).getUnit_id() + ",");
                        listChild.get(i).setSelect(true);
                    } else {
                        listChild.get(i).setSelect(false);
                    }
                }
            }
        });
        //重置
        tvReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flowlayoutOne.clearAllOption();
                flowLayoutTwo.clearAllOption();
                flowLayoutThree.clearAllOption();
            }
        });

    }

    /**
     * 完成
     */
    public static void OnWanCheng(TextView tvWancheng,final PopupWindows windows) {
        tvWancheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String one = sbXuan.toString();
                String two = sbXuan02.toString();
                String  unit_ids = one + two;
                if (two.equals("")){
                    unit_ids=one.substring(0,one.length()-1);
                }else{
                    unit_ids=two.substring(0,two.length()-1);
                }
//                unit_id=unit_ids.substring(0,unit_ids.length()-1);

                presenter.onSchoolRepor(IsStringSPUtils.IsUid(), "0", "0", unit_ids, "1", pgaeNum + "", pageSize + "",IsStringSPUtils.getSid());
                windows.dismiss();
//
//                clera();
//                tvSchDanYuan.setTextColor(MyApplication.instance.getResources().getColor(R.color.darkgreen));
            }
        });
    }

    /**
     * 删除Dialog
     */
    private void showExtraDialog() {
        dialog = new Dialog(getActivity(), R.style.rel_dialog);
        View view = LayoutInflater.from(getActivity()).inflate(
                R.layout.dialog_delete, null);
        dialog.setContentView(view);

        TextView dialog_ok = (TextView) view.findViewById(R.id.dialog_ok);
        TextView dialog_quxiao = (TextView) view.findViewById(R.id.dialog_quxiao);
        dialog.setCanceledOnTouchOutside(false);
        dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                showProgressDialog("删除中,请稍后", true);
                presenter.onDelet(uid,tid,IsStringSPUtils.getSid());

            }
        });
        dialog_quxiao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        // 屏幕宽度
        int screenWidth = display.getWidth();
        // 屏幕高度
        int screenHeight = display.getHeight();
        Window window = dialog.getWindow();

        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        lp.width = screenWidth * 3 / 4;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }

}
